package com.jianz.campus_markets.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jianz.campus_markets.domain.ResponseResult;
import com.jianz.campus_markets.domain.delay.DelayedOrder;
import com.jianz.campus_markets.domain.entity.Order;
import com.jianz.campus_markets.domain.entity.User;
import com.jianz.campus_markets.mapper.OrderMapper;
import com.jianz.campus_markets.service.OnDelayedListener;
import com.jianz.campus_markets.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianz.campus_markets.utils.RedisCache;
import com.jianz.campus_markets.utils.ThreadPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jianz
 * @since 2023-11-26
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService, InitializingBean {

    private static Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    private static final String ORDER_KEY = "orders";

    @Autowired
    DelayedService delayedService;

    @Autowired
    RedisCache redisService;

    @Autowired
    RestTemplate restTemplate;

    public void afterPropertiesSet() throws Exception{
        //系统启动，注册监听
        delayedService.registerListener(DelayedOrder.class, new OnDelayedListener<DelayedOrder>() {
            @Override
            public void onDelayedArrived(DelayedOrder order) {
                log.info("onDelayedArrived:{}", order.toString());
                //查询订单的状态
                String orderId = order.getValue().getId();
                int status = getFromDb(orderId).getStatus();
                if(status == 0) {//0代表未支付
                    //自动取消订单
                    System.out.println("取消订单");
                    //todo 部署时需要修改
                    String url = "http://localhost:8080/order/update?orderId=" + orderId;
                    restTemplate.getForEntity(url,ResponseResult.class);

                    //            autoCancelOrder(orderId.toString());
                }else if(status == 1){//1代表已经支付
                    //do nothing
                } else if(status == 2){//已经取消
                    //do nothing
                }
            }
        });
        //把redis中的订单重新插入队列
        ThreadPoolUtil.execute(()->{
            List<DelayedOrder> orders = redisService.getFromSet(ORDER_KEY, DelayedOrder.class);
            if(orders != null && orders.size() > 0) {
                for(DelayedOrder order : orders) {
                    delayedService.add(order);
                }
            }
        });
    }

    /**创建订单**/
    @Override
    public DelayedOrder createOrder(Order order) {

        if(order.getProductId() == 0){
            throw new RuntimeException("商品订单为空");
        }
        order.setStatus(0);

        String uuid = generate();
        order.setId(uuid);
        System.out.println(order);
        // 插入数据库
        getBaseMapper().insert(order);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getId, uuid);
        Order one = getOne(queryWrapper);
        log.info("订单{}创建完成，插入数据库", one.getId());
        DelayedOrder delayedOrder = new DelayedOrder(one);
        // 插入内存队列
        delayedService.add(delayedOrder);
        // 插入redis
        redisService.addToSet(ORDER_KEY, order);
        return delayedOrder;
    }

    /**支付订单**/
    public boolean payOrder(String orderId) {
        Order orderEntity = getFromDb(orderId);
        orderEntity.setStatus(1);
        // 修改数据库订单状态为已经支付
        updateById(orderEntity);
        log.info("订单{}支付完成", orderId);
        DelayedOrder order = delayedService.getDelayed(DelayedOrder.class, orderId);
        if(order != null) {
            // 从内存队列删除
            delayedService.remove(DelayedOrder.class, order);
            // 从redis删除
            redisService.deleteFromSet(ORDER_KEY, order);
        }
        return true;
    }


    /**自动取消订单**/
    public void autoCancelOrder(String orderId) {
        Order orderEntity = getFromDb(orderId);
        //修改数据库状态
        orderEntity.setStatus(2);
        // 修改数据库状态
        log.info("修改订单{}已经取消", orderEntity.getId());

        updateById(orderEntity);

        DelayedOrder order = delayedService.getDelayed(DelayedOrder.class, orderId);
        // 从内存队列删除
        delayedService.remove(DelayedOrder.class, order);
        // 从redis删除
        redisService.deleteFromSet(ORDER_KEY, order);
    }

    private Order getFromDb(String orderId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getId, orderId);
        Order order = getOne(queryWrapper);
        return order;
    }

    private String generate() {
        UUID uuid = UUID.randomUUID();

        return uuid.toString();
    }


    //获取用户的订单信息
    public List<Order> getOrderInfo(int userId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserid,userId);
       List<Order> orderList=baseMapper.selectList(queryWrapper);
       return orderList;
    }
}
